{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f198a97a-9d4c-41cd-b01d-e8b8d1cdd302",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/guodong.li/virtual-venv/peft-venv-py310-cu117/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import math\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import tempfile\n",
    "from torch.nn import TransformerEncoder, TransformerEncoderLayer\n",
    "\n",
    "if sys.platform == 'win32':\n",
    "    print('Windows platform is not supported for pipeline parallelism')\n",
    "    sys.exit(0)\n",
    "if torch.cuda.device_count() < 2:\n",
    "    print('Need at least two GPU devices for this tutorial')\n",
    "    sys.exit(0)\n",
    "\n",
    "class Encoder(nn.Module):\n",
    "    def __init__(self, ntoken, ninp, dropout=0.5):\n",
    "        super(Encoder, self).__init__()\n",
    "        self.pos_encoder = PositionalEncoding(ninp, dropout)\n",
    "        self.encoder = nn.Embedding(ntoken, ninp)\n",
    "        self.ninp = ninp\n",
    "        self.init_weights()\n",
    "\n",
    "    def init_weights(self):\n",
    "        initrange = 0.1\n",
    "        self.encoder.weight.data.uniform_(-initrange, initrange)\n",
    "\n",
    "    def forward(self, src):\n",
    "        # Need (S, N) format for encoder.\n",
    "        src = src.t()\n",
    "        src = self.encoder(src) * math.sqrt(self.ninp)\n",
    "        return self.pos_encoder(src)\n",
    "\n",
    "class Decoder(nn.Module):\n",
    "    def __init__(self, ntoken, ninp):\n",
    "        super(Decoder, self).__init__()\n",
    "        self.decoder = nn.Linear(ninp, ntoken)\n",
    "        self.init_weights()\n",
    "\n",
    "    def init_weights(self):\n",
    "        initrange = 0.1\n",
    "        self.decoder.bias.data.zero_()\n",
    "        self.decoder.weight.data.uniform_(-initrange, initrange)\n",
    "\n",
    "    def forward(self, inp):\n",
    "        # Need batch dimension first for output of pipeline.\n",
    "        return self.decoder(inp).permute(1, 0, 2)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "cd222a6c-a6fa-41b0-a9cb-fe07c0b093de",
   "metadata": {},
   "outputs": [],
   "source": [
    "class PositionalEncoding(nn.Module):\n",
    "\n",
    "    def __init__(self, d_model, dropout=0.1, max_len=5000):\n",
    "        super(PositionalEncoding, self).__init__()\n",
    "        self.dropout = nn.Dropout(p=dropout)\n",
    "\n",
    "        pe = torch.zeros(max_len, d_model)\n",
    "        position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)\n",
    "        div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))\n",
    "        pe[:, 0::2] = torch.sin(position * div_term)\n",
    "        pe[:, 1::2] = torch.cos(position * div_term)\n",
    "        pe = pe.unsqueeze(0).transpose(0, 1)\n",
    "        self.register_buffer('pe', pe)\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = x + self.pe[:x.size(0), :]\n",
    "        return self.dropout(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "45263f86-cc4b-4f4f-9f25-967eefd96e2e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "from torchtext.datasets import WikiText2\n",
    "from torchtext.data.utils import get_tokenizer\n",
    "from torchtext.vocab import build_vocab_from_iterator\n",
    "\n",
    "train_iter = WikiText2(split='train')\n",
    "tokenizer = get_tokenizer('basic_english')\n",
    "vocab = build_vocab_from_iterator(map(tokenizer, train_iter), specials=[\"<unk>\"])\n",
    "vocab.set_default_index(vocab[\"<unk>\"])\n",
    "\n",
    "def data_process(raw_text_iter):\n",
    "  data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter]\n",
    "  return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))\n",
    "\n",
    "train_iter, val_iter, test_iter = WikiText2()\n",
    "train_data = data_process(train_iter)\n",
    "val_data = data_process(val_iter)\n",
    "test_data = data_process(test_iter)\n",
    "\n",
    "device = torch.device(\"cuda\")\n",
    "\n",
    "def batchify(data, bsz):\n",
    "    # Divide the dataset into ``bsz`` parts.\n",
    "    nbatch = data.size(0) // bsz\n",
    "    # Trim off any extra elements that wouldn't cleanly fit (remainders).\n",
    "    data = data.narrow(0, 0, nbatch * bsz)\n",
    "    # Evenly divide the data across the ``bsz` batches.\n",
    "    data = data.view(bsz, -1).t().contiguous()\n",
    "    return data.to(device)\n",
    "\n",
    "batch_size = 20\n",
    "eval_batch_size = 10\n",
    "train_data = batchify(train_data, batch_size)\n",
    "val_data = batchify(val_data, eval_batch_size)\n",
    "test_data = batchify(test_data, eval_batch_size)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "df9a8520-c6a5-49bd-a1df-7bf6ee44a4c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "bptt = 25\n",
    "def get_batch(source, i):\n",
    "    seq_len = min(bptt, len(source) - 1 - i)\n",
    "    data = source[i:i+seq_len]\n",
    "    target = source[i+1:i+1+seq_len].view(-1)\n",
    "    # Need batch dimension first for pipeline parallelism.\n",
    "    return data.t(), target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cb0fe3ff-f65f-4635-b221-beb17758a6e1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tmpfile: /tmp/tmp37b004v1\n",
      "Total parameters in model: 1,444,261,998\n",
      "Pipe(\n",
      "  (partitions): ModuleList(\n",
      "    (0): PipeSequential(\n",
      "      (0): Encoder(\n",
      "        (pos_encoder): PositionalEncoding(\n",
      "          (dropout): Dropout(p=0.2, inplace=False)\n",
      "        )\n",
      "        (encoder): Embedding(28782, 4096)\n",
      "      )\n",
      "      (1): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (2): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (3): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (4): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (5): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (6): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "    )\n",
      "    (1): PipeSequential(\n",
      "      (0): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (1): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (2): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (3): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (4): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (5): TransformerEncoderLayer(\n",
      "        (self_attn): MultiheadAttention(\n",
      "          (out_proj): NonDynamicallyQuantizableLinear(in_features=4096, out_features=4096, bias=True)\n",
      "        )\n",
      "        (linear1): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (dropout): Dropout(p=0.2, inplace=False)\n",
      "        (linear2): Linear(in_features=4096, out_features=4096, bias=True)\n",
      "        (norm1): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (norm2): LayerNorm((4096,), eps=1e-05, elementwise_affine=True)\n",
      "        (dropout1): Dropout(p=0.2, inplace=False)\n",
      "        (dropout2): Dropout(p=0.2, inplace=False)\n",
      "      )\n",
      "      (6): Decoder(\n",
      "        (decoder): Linear(in_features=4096, out_features=28782, bias=True)\n",
      "      )\n",
      "    )\n",
      "  )\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "ntokens = len(vocab) # the size of vocabulary\n",
    "emsize = 4096 # embedding dimension\n",
    "nhid = 4096 # the dimension of the feedforward network model in ``nn.TransformerEncoder``\n",
    "nlayers = 12 # the number of ``nn.TransformerEncoderLayer`` in ``nn.TransformerEncoder``\n",
    "nhead = 16 # the number of heads in the Multihead Attention models\n",
    "dropout = 0.2 # the dropout value\n",
    "\n",
    "from torch.distributed import rpc\n",
    "tmpfile = tempfile.NamedTemporaryFile()\n",
    "\n",
    "print(\"tmpfile:\", tmpfile.name)\n",
    "\n",
    "rpc.init_rpc(\n",
    "    name=\"worker\",\n",
    "    rank=0,\n",
    "    world_size=1,\n",
    "    rpc_backend_options=rpc.TensorPipeRpcBackendOptions(\n",
    "        init_method=\"file://{}\".format(tmpfile.name),\n",
    "        # Specifying _transports and _channels is a workaround \n",
    "        # 对于 PyTorch 版本 >= 1.8.1 时，不再必须指定 specify _transports 和 _channels 。\n",
    "        _transports=[\"ibv\", \"uv\"],\n",
    "        _channels=[\"cuda_ipc\", \"cuda_basic\"],\n",
    "    )\n",
    ")\n",
    "\n",
    "num_gpus = 2\n",
    "partition_len = ((nlayers - 1) // num_gpus) + 1\n",
    "\n",
    "# Add encoder in the beginning.\n",
    "# 手动指定cuda0\n",
    "tmp_list = [Encoder(ntokens, emsize, dropout).cuda(0)]\n",
    "module_list = []\n",
    "\n",
    "# Add all the necessary transformer blocks.\n",
    "for i in range(nlayers):\n",
    "    transformer_block = TransformerEncoderLayer(emsize, nhead, nhid, dropout)\n",
    "    if i != 0 and i % (partition_len) == 0:\n",
    "        module_list.append(nn.Sequential(*tmp_list))\n",
    "        tmp_list = []\n",
    "    device = i // (partition_len)\n",
    "    tmp_list.append(transformer_block.to(device))\n",
    "\n",
    "# Add decoder in the end.\n",
    "# 手动指定cuda1\n",
    "tmp_list.append(Decoder(ntokens, emsize).cuda(num_gpus - 1))\n",
    "\n",
    "module_list.append(nn.Sequential(*tmp_list))\n",
    "\n",
    "from torch.distributed.pipeline.sync import Pipe\n",
    "\n",
    "# Build the pipeline.\n",
    "chunks = 8\n",
    "model = Pipe(torch.nn.Sequential(*module_list), chunks = chunks)\n",
    "\n",
    "\n",
    "def get_total_params(module: torch.nn.Module):\n",
    "    total_params = 0\n",
    "    for param in module.parameters():\n",
    "        total_params += param.numel()\n",
    "    return total_params\n",
    "\n",
    "print ('Total parameters in model: {:,}'.format(get_total_params(model)))\n",
    "print(model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f3f464dc-e9ba-42bb-a4d4-fa6c0a5073d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "criterion = nn.CrossEntropyLoss()\n",
    "lr = 5.0 # learning rate\n",
    "optimizer = torch.optim.SGD(model.parameters(), lr=lr)\n",
    "scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 1.0, gamma=0.95)\n",
    "\n",
    "import time\n",
    "def train():\n",
    "    model.train() # Turn on the train mode\n",
    "    total_loss = 0.\n",
    "    start_time = time.time()\n",
    "    ntokens = len(vocab)\n",
    "\n",
    "    # Train only for 50 batches to keep script execution time low.\n",
    "    nbatches = min(50 * bptt, train_data.size(0) - 1)\n",
    "\n",
    "    for batch, i in enumerate(range(0, nbatches, bptt)):\n",
    "        data, targets = get_batch(train_data, i)\n",
    "        optimizer.zero_grad()\n",
    "        # Since the Pipe is only within a single host and process the ``RRef``\n",
    "        # returned by forward method is local to this node and can simply\n",
    "        # retrieved via ``RRef.local_value()``.\n",
    "        output = model(data).local_value()\n",
    "        # Need to move targets to the device where the output of the\n",
    "        # pipeline resides.\n",
    "        loss = criterion(output.view(-1, ntokens), targets.cuda(1))\n",
    "        loss.backward()\n",
    "        torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n",
    "        optimizer.step()\n",
    "\n",
    "        total_loss += loss.item()\n",
    "        log_interval = 10\n",
    "        if batch % log_interval == 0 and batch > 0:\n",
    "            cur_loss = total_loss / log_interval\n",
    "            elapsed = time.time() - start_time\n",
    "            print('| epoch {:3d} | {:5d}/{:5d} batches | '\n",
    "                  'lr {:02.2f} | ms/batch {:5.2f} | '\n",
    "                  'loss {:5.2f} | ppl {:8.2f}'.format(\n",
    "                    epoch, batch, nbatches // bptt, scheduler.get_lr()[0],\n",
    "                    elapsed * 1000 / log_interval,\n",
    "                    cur_loss, math.exp(cur_loss)))\n",
    "            total_loss = 0\n",
    "            start_time = time.time()\n",
    "\n",
    "def evaluate(eval_model, data_source):\n",
    "    eval_model.eval() # Turn on the evaluation mode\n",
    "    total_loss = 0.\n",
    "    ntokens = len(vocab)\n",
    "    # Evaluate only for 50 batches to keep script execution time low.\n",
    "    nbatches = min(50 * bptt, data_source.size(0) - 1)\n",
    "    with torch.no_grad():\n",
    "        for i in range(0, nbatches, bptt):\n",
    "            data, targets = get_batch(data_source, i)\n",
    "            output = eval_model(data).local_value()\n",
    "            output_flat = output.view(-1, ntokens)\n",
    "            # Need to move targets to the device where the output of the\n",
    "            # pipeline resides.\n",
    "            total_loss += len(data) * criterion(output_flat, targets.cuda(1)).item()\n",
    "    return total_loss / (len(data_source) - 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a85df730-3c8d-48aa-b730-81239070f49b",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/guodong.li/virtual-venv/peft-venv-py310-cu117/lib/python3.10/site-packages/torch/optim/lr_scheduler.py:381: UserWarning: To get the last learning rate computed by the scheduler, please use `get_last_lr()`.\n",
      "  warnings.warn(\"To get the last learning rate computed by the scheduler, \"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "| epoch   1 |    10/   50 batches | lr 5.00 | ms/batch 507.00 | loss 42.58 | ppl 3094654443538114560.00\n",
      "| epoch   1 |    20/   50 batches | lr 5.00 | ms/batch 380.02 | loss 41.60 | ppl 1161863941711398144.00\n",
      "| epoch   1 |    30/   50 batches | lr 5.00 | ms/batch 361.34 | loss 42.50 | ppl 2871363680581511680.00\n",
      "| epoch   1 |    40/   50 batches | lr 5.00 | ms/batch 372.07 | loss 40.63 | ppl 441516461309450688.00\n",
      "-----------------------------------------------------------------------------------------\n",
      "| end of epoch   1 | time: 22.27s | valid loss  0.97 | valid ppl     2.64\n",
      "-----------------------------------------------------------------------------------------\n",
      "| epoch   2 |    10/   50 batches | lr 4.51 | ms/batch 401.81 | loss 39.16 | ppl 101713356373353456.00\n",
      "| epoch   2 |    20/   50 batches | lr 4.51 | ms/batch 374.01 | loss 29.01 | ppl 3985883147930.86\n",
      "| epoch   2 |    30/   50 batches | lr 4.51 | ms/batch 378.12 | loss 26.52 | ppl 329134739848.90\n",
      "| epoch   2 |    40/   50 batches | lr 4.51 | ms/batch 382.70 | loss 20.50 | ppl 802992471.18\n",
      "-----------------------------------------------------------------------------------------\n",
      "| end of epoch   2 | time: 21.53s | valid loss  0.38 | valid ppl     1.46\n",
      "-----------------------------------------------------------------------------------------\n",
      "| epoch   3 |    10/   50 batches | lr 4.29 | ms/batch 416.74 | loss 13.64 | ppl 842059.77\n",
      "| epoch   3 |    20/   50 batches | lr 4.29 | ms/batch 368.97 | loss 10.73 | ppl 45837.47\n",
      "| epoch   3 |    30/   50 batches | lr 4.29 | ms/batch 366.39 | loss 10.70 | ppl 44182.25\n",
      "| epoch   3 |    40/   50 batches | lr 4.29 | ms/batch 364.48 | loss 11.38 | ppl 87633.96\n",
      "-----------------------------------------------------------------------------------------\n",
      "| end of epoch   3 | time: 21.07s | valid loss  0.21 | valid ppl     1.24\n",
      "-----------------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "best_val_loss = float(\"inf\")\n",
    "epochs = 3 # The number of epochs\n",
    "best_model = None\n",
    "\n",
    "for epoch in range(1, epochs + 1):\n",
    "    epoch_start_time = time.time()\n",
    "    # 训练\n",
    "    train()\n",
    "    # 评估\n",
    "    val_loss = evaluate(model, val_data)\n",
    "    print('-' * 89)\n",
    "    print('| end of epoch {:3d} | time: {:5.2f}s | valid loss {:5.2f} | '\n",
    "          'valid ppl {:8.2f}'.format(epoch, (time.time() - epoch_start_time),\n",
    "                                     val_loss, math.exp(val_loss)))\n",
    "    print('-' * 89)\n",
    "\n",
    "    if val_loss < best_val_loss:\n",
    "        best_val_loss = val_loss\n",
    "        best_model = model\n",
    "\n",
    "    scheduler.step()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "2ed6c897-5982-4a49-aafa-6c18d1c7e8e2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "=========================================================================================\n",
      "| End of training | test loss  0.19 | test ppl     1.21\n",
      "=========================================================================================\n"
     ]
    }
   ],
   "source": [
    "test_loss = evaluate(best_model, test_data)\n",
    "print('=' * 89)\n",
    "print('| End of training | test loss {:5.2f} | test ppl {:8.2f}'.format(\n",
    "    test_loss, math.exp(test_loss)))\n",
    "print('=' * 89)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20438970-1e54-4959-ad48-7eb506fc0405",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "peft-venv-py310-cu117",
   "language": "python",
   "name": "peft-venv-py310-cu117"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
